<template>
  <div>
    <el-tabs type="card" @tab-click="handleTabClick" v-model="activeTab" >
      <el-tab-pane label="用户管理" name="update">用户管理
        <el-container>
          <el-table :data="tableData"  stripe style="width: 100%" >
            <el-table-column prop="id" label="ID"  align="center" sortable></el-table-column>
            <el-table-column prop="username" label="用户名" align="center"></el-table-column>
            <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
            <el-table-column prop="phone" label="手机号码" align="center"></el-table-column>
            <el-table-column prop="createTime" label="创建日期" width="180" align="center" sortable>
              <template slot-scope="scope">
                {{scope.row.createTime | moment("YYYY-MM-DD HH:mm:ss")}}
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更改日期" width="180" align="center" sortable>
              <template slot-scope="scope">
                {{scope.row.updateTime | moment("YYYY-MM-DD HH:mm:ss")}}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                <el-button
                  v-if="scope.row.isDelete === 0"
                  size="mini"
                  type="danger"
                  @click="handleAction(scope.row, 'user', 'delete')">删除</el-button>
                <el-button
                  v-else
                  size="mini"
                  type="info"
                  @click="handleAction(scope.row, 'user', 'restore')">恢复</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-container>
        <el-row>
          <el-pagination
            background
            layout="prev, pager, next"
            :total="userPage.pageSize">
          </el-pagination>
        </el-row>
      </el-tab-pane>
      <el-tab-pane label="新增用户" name="add">
        <div class="registerForm">
          <el-form :model="userForm" :rules="rules" ref="userForm">
          <p>新增用户</p>
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="userForm.password" autocomplete="off" type="password"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="rePassword">
              <el-input v-model="userForm.rePassword" autocomplete="off" type="password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="phone">
              <el-input v-model="userForm.phone" autocomplete="off"></el-input>
            </el-form-item>
            <!--<el-form-item label="用户类型" prop="type">-->
            <!--<el-select v-model="userForm.type" placeholder="选择用户类型" value="">-->
            <!--<el-option label="管理员" value="0"></el-option>-->
            <!--<el-option label="普通用户" value="1"></el-option>-->
            <!--</el-select>-->
            <!--</el-form-item>-->
            <el-button type="primary" @click="submitForm('userForm')">提交</el-button>
          </el-form>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  name: 'User',
  data () {
    return {
      userPage: {
        currentPage: 1,
        pageSize: 10,
        total: 10
      },
      pageSize: 10,
      currentPage: 1,
      activeTab: 'update',
      tableData: [],
      userForm: {
        id: '',
        username: '',
        password: '',
        rePassword: '',
        email: '',
        phone: '',
        type: '',
        registrationInfo: '',
        createTime: '',
        updateTime: '',
        isDelete: ''
      },
      dialogFormVisible: false,
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, message: '用户名用户名最少两个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度为6-16位', trigger: 'blur' }
        ],
        rePassword: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { validator: this.validateRePassword, trigger: 'blur' }
        ],
        email: [
          { type: 'email', required: true, message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入正确的手机号码', trigger: 'blur' },
          {pattern: /^1[34578]\d{9}$/, message: '请输入长度为11位的手机号码'}
        ]
      }
    }
  },
  methods: {
    getUsers: function () {
      this.axios.get(getGServerUrl() + '/user/find/pages', {
        params: {
          index: this.currentPage,
          pageSize: this.pageSize
        }
      })
        .then(response => {
          let users = response.data.data.user
          this.tableData = users.list
          this.userPage.pageSize = users.pageSize
        })
    },
    handleTabClick (tab, event) {
      // console.log(tab, event)
      if (tab.name === 'add') {
        this.$refs['userForm'].resetFields()
      }
    },
    handleEdit: function (index, row) {
      console.log(row)
      this.userForm = row
      this.activeTab = 'add'
    },
    submitForm (formName) {
      let action = ''
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = getGServerUrl()
          console.log(this.userForm.id)
          if (this.userForm.id === '') {
            url += '/user/add'
            action = 'add'
          } else {
            url += '/user/update'
            action = 'update'
          }
          this.axios.post(url, this.userForm)
            .then(response => {
              console.log(response)
              if (response.data.data.count > 0) {
                this.$message({
                  message: '新增成功:200',
                  type: 'success'
                })
                this.$refs[formName].resetFields()
                this.activeTab = 'update'
                this.getUsers()
              }
            })
            .catch(error => {
              let msg = ''
              if (action === 'add') {
                msg = '新增用户失败 '
              } else {
                msg = '更新用户失败 '
              }
              this.$message({
                message: msg + error,
                type: 'error'
              })
            })
        } else {
          this.$message({
            message: '操作失败，请检查输入是否正确',
            type: 'error'
          })
        }
      })
    },
    validateRePassword (rule, value, callback) {
      if (value !== this.userForm.password) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    },
    handleAction: function (row, type, action) {
      let msgAction = ''
      let requestUrl = getGServerUrl()
      requestUrl = requestUrl + '/' + type + '/' + action + '/' + row.id
      this.axios.delete(requestUrl).then(response => {
        let count = response.data.data.count
        if (count > 0) {
          if (action === 'delete') {
            row.isDelete = 1
            msgAction = '删除'
          } else if (action === 'restore') {
            row.isDelete = 0
            msgAction = '恢复'
          }
          this.$message({
            message: msgAction + '成功：' + count,
            type: 'success'
          })
        }
      })
        .catch(error => {
          if (action === 'delete') {
            msgAction = '删除'
          } else if (action === 'restore') {
            msgAction = '恢复失败'
          }
          this.$message({
            message: msgAction + '失败: ' + error,
            type: 'error'
          })
        })
    }
  },
  mounted: function () {
    this.getUsers()
  }
}
</script>

<style scoped>
  .registerForm{
    text-align: center;
  }
  .el-form{
    width: 400px;
    display: inline-block;
    border: solid 1px #bdc8d6;
    padding: 20px;
  }
.el-row{
  text-align: center;
  padding: 20px;
}
</style>
